package com.jv.linearlayoutlearning;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class FrameLayoutLeaning extends AppCompatActivity {

    private FrameLayout frameLayoutTest;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frame_layout);
        frameLayoutTest = findViewById(R.id.FrameLayoutTest);
        MoveView moveView = new MoveView(this);
        moveView.setOnTouchListener((view, motionEvent) -> {
            // 设置显示的位置
            moveView.setVarX(motionEvent.getX());
            moveView.setVarY(motionEvent.getY());
            // 调用重绘方法
            moveView.invalidate();

            return true;
        });
        frameLayoutTest.addView(moveView);
    }
    class MoveView extends View {

        float x, y;
        public MoveView(Context context) {
            super(context);
            x = 50;
            y = 100;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //创建,并且实例化Paint的对象
            Paint paint = new Paint();
            //根据图片生成位图对象
            Bitmap bitmap = BitmapFactory.decodeResource(getResources() ,R.drawable.image1);
            // 绘制
            canvas.drawBitmap(bitmap, x, y, paint);
            // 判断图片是否被回收,没有回收就强制回收
            if(bitmap.isRecycled())
                bitmap.recycle();
        }

        public void setVarX(float x) {
            this.x = x;
        }

        public void setVarY(float y) {
            this.y = y;
        }
    }
}
